package com.XinYun.Library.modules.Register.Servlet;

import com.XinYun.Library.modules.Login.Service.SendEmail;
import com.XinYun.Library.modules.Register.EmailUtil;
import com.XinYun.Library.modules.commons.ResponseWrapper.ResponseWrapper;
import com.XinYun.Library.utils.SqlUtils.DruidUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

@WebServlet(name = "SendEmailServlet", value = "/SendEmailServlet")
public class SendEmailServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        BufferedReader reader = request.getReader();
        String readerLine = reader.readLine();
        JSONObject jsonObject = JSON.parseObject(readerLine);
        String mail = jsonObject.getString("Register_mail");

        HttpSession session = request.getSession();

        //服务器通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");

        String base = "0123456789ABCDEFGHIJKLMNOPQRSDUVWXYZabcdefghijklmnopqrsduvwxyz";
        int size = base.length();
        Random r = new Random();
        StringBuilder code = new StringBuilder();
        for(int i=1;i<=6;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            code.append(c);
        }
        //把验证码保存在session中，方便后续判断
        session.setAttribute("EmailCode",code.toString());
        //实例化一个发送邮件的对象
        EmailUtil emailUtil = new EmailUtil();
        //发送邮件
        emailUtil.giveRcode(mail, "您好，您的注册验证码是：" + code.toString() +"\n请正确输入您的验证码！如非本人操作，请忽略。");
        ResponseWrapper responseWrapper = null;
        responseWrapper = ResponseWrapper.SendSuccess();
        String s = JSON.toJSONString(responseWrapper);
        PrintWriter writer = response.getWriter();
        writer.println(s);
        System.out.println(s);
        }
    }
